import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.ResultSet;
import java.util.Scanner;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCDemo {
    public static void main(String[] args) throws SQLException {
        // 接下来通过 JDBC 进行一个简单的 插入数据 的操作.
        // JDBC 代码写起来, 对于初学者来说, 有一点 "繁琐" . (接下来会见到很多新的概念, 新的类, 新的方法).
        // 步骤会比较多. 每个步骤都不难, 都是 "固定讨论"

        // 1. 创建 "数据源" (DataSource)
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test3?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("1234");
        // 和数据库服务器连接

        Connection   connection = (Connection) dataSource.getConnection();
            // 这里写你的业务逻辑
     Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的学号");
        int id  =  scanner.nextInt();
        System.out.println("请输入你的名字");
        String name = scanner.next();

        //String sql = "insert into student values(1,'张三')";
        String sql = "insert into student values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);
        //
        int n = preparedStatement.executeUpdate();
        System.out.println(n);

        //执行sql
        String querySql = "SELECT * FROM student";
        PreparedStatement queryStatement = connection.prepareStatement(querySql);
        ResultSet resultSet = queryStatement.executeQuery();
        while(resultSet.next()){
             id = resultSet.getInt("id");
             name = resultSet.getString("name");
            System.out.println("id = "+ id + ", name = "+name);
        }

        // 释放资源
        resultSet.close();
        queryStatement.close();
        preparedStatement.close();
        connection.close();


    }
}